/**
 *@author lk
 *@date 2022/4/22 22:08 
 */
package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_cms.dao.CmsPageRepository;
import org.junit.runners.ParentRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class CmsPageService {

    @Autowired
    CmsPageRepository cmsPageRepository;

    /**
     *
     * @param page 从1开始计数的
     * @param size
     * @param queryPageRequest
     * @return
     */
    public QueryResponseResult findAll(int page, int size, QueryPageRequest queryPageRequest) {
        //检查参数
        page = checkPage(page);
        size = checkSize(size);

        PageRequest pageRequest = PageRequest.of(page, size);
        Page<CmsPage> cmsPages = cmsPageRepository.findAll(pageRequest);

        QueryResult<CmsPage> queryResult = getCmsPageQueryResult(cmsPages);

        QueryResponseResult queryResponseResult = new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        return queryResponseResult;
    }

    private QueryResult<CmsPage> getCmsPageQueryResult(Page<CmsPage> cmsPages) {
        QueryResult<CmsPage> queryResult = new QueryResult<>();
        queryResult.setList(cmsPages.getContent());
        queryResult.setTotal(cmsPages.getTotalElements());
        return queryResult;
    }

    private int checkSize(int size) {
        if (size <= 0) {
            size =10;
        }
        return size;
    }

    private int checkPage(int page) {
        if (page <= 0) {
            page = 1;
        }
        page -= 1;
        return page;
    }


}
